﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Telerik.Web.UI.Skins;
using Telerik.Web.UI;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.ModelService;
using RN.ERP.Web.PersonService;
using RN.ERP.Web.BasicService;

namespace RN.ERP.Web.Person
{
    public partial class PersonExpertList : BasePage
    {
        #region Params
        public string DBCode
        {
            get
            {
                return this.Request.QueryString["areacode"] == null ? UserInfo.LocalArea : this.Request.QueryString["areacode"].ToString();
            }
        }
        public string FlowCode
        {
            get
            {
                return this.Request.QueryString["flowcode"] == null ? string.Empty : this.Request.QueryString["flowcode"].ToString();
            }
        }
        /// <summary>
        /// 表示是否是老专家统计
        /// </summary>
        private bool isOldExpert 
        { 
            get 
            {
                return Request.QueryString["isOldExpert"] == "true";
            } 
        }
        /// <summary>
        /// 是否是有条件通过
        /// </summary>
        protected string IsLimitedPass
        {
            get
            {
                return hidIsLimitedPass.Value;
            }
        }
        BasicServiceClient basicServiceClient = new BasicServiceClient();
        PersonServiceClient personClient = new PersonServiceClient();
        #endregion

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindFlowCode();

                string flowType = Request.QueryString["flowCode"];
                if (!isOldExpert || (!String.IsNullOrEmpty(flowType)
                    && !"FlowType22,FlowType31,FlowType32,FlowType41".Contains(flowType)))
                {
                    auditDiv.Visible = false;
                }
            }
        }

        protected void ListExperts_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
        {
            int pageSize = ListExperts.PageSize;
            int pageIndex = ListExperts.CurrentPageIndex + 1;
            int count = 0;
            string experts = String.Empty;
            var queryCondition = hdnCondition.Value;
            if (string.IsNullOrEmpty(queryCondition))
            {
                queryCondition = GetCondition();
            }
            if (isOldExpert)
            {
                experts = personClient.GetOldExpertList(pageIndex, pageSize, GetOldExpertCondition(), out count);
            }
            else
            {
                experts = personClient.GetExpertsList(pageIndex, pageSize, queryCondition, "00", out count);
            }
            var listExperts = JsonConvert.DeserializeObject<IList<tb_Emp_Manager>>(experts).ToList();
            int cnt = count;
            ListExperts.VirtualItemCount = cnt;
            ListExperts.DataSource = listExperts;
        }

        /// <summary>
        /// 获取老专家列表条件
        /// 注意：传递的条件老专家有别于新专家  老专家传递一个条件对象，新专家是一个条件列表
        /// </summary>
        private string GetOldExpertCondition()
        {
            QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
            string title = txtTitle.Text.Trim();
            condition.Name = new ParameterValue<string>() { O = OptEnum.Like, V = title };
            condition.AreaCode = new ParameterValue<string> { O = OptEnum.Equal, V = Request.QueryString["areaCode"] };
            condition.FlowCode = new ParameterValue<string> { O = OptEnum.Equal, V = Request.QueryString["flowCode"] };
            condition.TypeFlag = new ParameterValue<string> { O = OptEnum.Equal, V = ddlAuditType.SelectedValue };
            return JsonConvert.SerializeObject(condition);
        }

        ////获取查询条件
        private string GetCondition()
        {
            List<string> listFlow = GetFlowCodes();
            List<QueryPersonInfoCondition> queryList = new List<QueryPersonInfoCondition>();
            foreach (var f in listFlow)
            {
                QueryPersonInfoCondition condition = new QueryPersonInfoCondition();
                string title = txtTitle.Text.Trim();
                if (!string.IsNullOrEmpty(title))
                {
                    condition.Name = new ParameterValue<string>() { O = OptEnum.Like, V = title };
                }
                condition.isShenBao = new ParameterValue<byte?>() { O = OptEnum.Equal, V = null };
                condition.FlowCode = new ParameterValue<string>() { O = OptEnum.Equal, V = f };
                if (!string.IsNullOrEmpty(DBCode)&&DBCode!="00")
                {
                    condition.AreaCode = new ParameterValue<string>() { O = OptEnum.StartWith, V = DBCode };
                    if (DBCode != "01" && UserInfo.RoleId != null && UserInfo.RoleId == "87")
                    {
                        if (DBCode == UserInfo.LocalArea)
                        {
                            if (f == "0,019" || f == "0,019,022")
                            {
                                string area = DBCode.Substring(0, 2) + "01";
                                condition.AreaCode = new ParameterValue<string>() { O = OptEnum.Equal, V = area };
                            }
                        }
                    }
                }
                queryList.Add(condition);
            }
            return JsonConvert.SerializeObject(queryList);
        }

        /// <summary>
        /// 判断已选中的专家中是否有无权审核的
        /// </summary>
        /// <param name="flowDic">人员Guid，FlowCode组成的字典</param>
        /// <returns>不符条件的人员GUID集合</returns>
        private List<string> CheckSelectedItems(Dictionary<string,string> flowDic)
        {
            List<string> rstList = new List<string>();
            
            ////判断是否是使用专家系统的市级主管
            if (!DBCode.StartsWith("01") && UserInfo.RoleId != null && UserInfo.RoleId == "87")
            {
                foreach (var item in flowDic)
                {
                    if (item.Value == "0,019" || item.Value == "0,019,022")
                    {
                        rstList.Add(item.Key);
                    }
                }
            }
            return rstList;
        }

        /// <summary>
        /// 客户端grid刷新
        /// </summary>
        protected void RadAjaxManager1_AjaxRequest(object sender, AjaxRequestEventArgs e)
        {
            switch (e.Argument)
            {
                case "Rebind":
                    ListExperts.MasterTableView.SortExpressions.Clear();
                    ListExperts.MasterTableView.GroupByExpressions.Clear();
                    ListExperts.Rebind();
                    break;
                case "Audit":
                try
                {
                    int checkCount = 0;
                    string strGuid = string.Empty;
                    string comments = hdnComments.Value;
                    List<string> list = new List<string>();
                    Dictionary<string, string> flowDic = new Dictionary<string, string>();

                    foreach (GridDataItem dataItem in ListExperts.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            strGuid = dataItem.GetDataKeyValue("EmpGuid").ToString();
                            checkCount++;
                            list.Add(strGuid);
                            flowDic.Add(strGuid, dataItem["FlowCode"].Text);
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要审核的数据！');", true);
                    }
                    else if (checkCount >= 1)
                    {
                        string ret = AuditExpert(list, "5", flowDic, "评标专家审核");
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                        if (result.Result == true)
                        {
                            ListExperts.Rebind();
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    hidSysError.Value = ex.Message;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
                break;
                case "Back":
                try
                {
                    int checkCount = 0;
                    string strGuid = string.Empty;
                    List<string> list = new List<string>();
                    Dictionary<string, string> flowDic = new Dictionary<string, string>();

                    foreach (GridDataItem dataItem in ListExperts.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            strGuid = dataItem.GetDataKeyValue("EmpGuid").ToString();
                            checkCount++;
                            list.Add(strGuid);
                            flowDic.Add(strGuid, dataItem["FlowCode"].Text);
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要退回的数据！');", true);
                    }
                    else if (checkCount >= 1)
                    {
                        string ret = AuditExpert(list, "6", flowDic, "评标专家退回");
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                        if (result.Result == true)
                        {
                            ListExperts.Rebind();
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    hidSysError.Value = ex.Message;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
                break;
                case "UnlockBack":
                try
                {
                    int checkCount = 0;
                    string strGuid = string.Empty;
                    List<string> list = new List<string>();
                    Dictionary<string, string> flowDic = new Dictionary<string, string>();

                    foreach (GridDataItem dataItem in ListExperts.MasterTableView.Items)
                    {
                        if ((dataItem.FindControl("CheckBox1") as CheckBox).Checked == true)
                        {
                            strGuid = dataItem.GetDataKeyValue("EmpGuid").ToString();
                            checkCount++;
                            list.Add(strGuid);
                            flowDic.Add(strGuid, dataItem["FlowCode"].Text);
                        }
                    }
                    if (checkCount == 0)
                    {
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('请选择要解锁退回的数据！');", true);
                    }
                    else if (checkCount >= 1)
                    {
                        string ret = AuditExpert(list, "7", flowDic, "评标专家解锁退回");
                        OperationResult result = JsonConvert.DeserializeObject<OperationResult>(ret);
                        if (result.Result == true)
                        {
                            ListExperts.Rebind();
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('" + result.Message + "');", true);
                        }
                    }
                }
                catch (Exception ex)
                {
                    hidSysError.Value = ex.Message;
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "", "alert('数据加载失败！');", true);
                }
                break;
                default:
                    break;
            }
        }

        private string AuditExpert(List<string> data, string opt, Dictionary<string, string> flowDic, string content)
        {
            
            if (CheckSelectedItems(flowDic).Count > 0)
            {
                OperationResult rst = new OperationResult
                {
                    Result = false,
                    Message = "操作失败，请检查专家的审核状态。"
                };
                return JsonConvert.SerializeObject(rst);
            }

            string currentAreaCode = UserInfo.CurrentArea;
            
            User_Log log = new User_Log();
            log.IsrtUserArea = IsLimitedPass;
            log.FunctionId = opt;
            log.FunctionType = content;
            log.Notice = hdnComments.Value;

            var result = personClient.ExpertInfoPost(UserInfo.CorpUserGuid,JsonConvert.SerializeObject(data),JsonConvert.SerializeObject(log),currentAreaCode);
            return result;
        }

        protected void ToggleRowSelection(object sender, EventArgs e)
        {
            ((sender as CheckBox).NamingContainer as GridItem).Selected = (sender as CheckBox).Checked;
            bool checkHeader = true;
            foreach (GridDataItem dataItem in ListExperts.MasterTableView.Items)
            {
                if (!(dataItem.FindControl("CheckBox1") as CheckBox).Checked)
                {
                    checkHeader = false;
                    break;
                }
            }
            GridHeaderItem headerItem = ListExperts.MasterTableView.GetItems(GridItemType.Header)[0] as GridHeaderItem;
            (headerItem.FindControl("headerChkbox") as CheckBox).Checked = checkHeader;
        }

        protected void ToggleSelectedState(object sender, EventArgs e)
        {
            CheckBox headerCheckBox = (sender as CheckBox);
            foreach (GridDataItem dataItem in ListExperts.MasterTableView.Items)
            {
                (dataItem.FindControl("CheckBox1") as CheckBox).Checked = headerCheckBox.Checked;
                dataItem.Selected = headerCheckBox.Checked;
            }
        }

        private void BindFlowCode()
        {
            string msg = string.Empty;
            var dic = JsonConvert.DeserializeObject<Dictionary<string, string>>(basicServiceClient.GetAllBusinessStatusAndProcessing(out msg,UserInfo.RoleId,"00","8065",true));
            ddlStatus.Items.Clear();
            foreach (var key in dic.Keys)
            {
                ddlStatus.Items.Add(new ListItem(dic[key],key));
            }
            if (dic.ContainsKey("处理中"))
            {
                ddlStatus.Items.FindByText("处理中").Selected = true;
            }
        }

        private List<string> GetFlowCodes()
        {
            if (!string.IsNullOrEmpty(FlowCode))
            {
                ddlStatus.Visible = false;
                string flowCode = FlowCode;
                List<string> listFlow = new List<string>();
                foreach (var f in flowCode.Split(';'))
                {
                    if (!string.IsNullOrEmpty(f))
                    {
                        listFlow.Add(f);
                    }
                }
                return listFlow;
            }
            else
            {
                string flowCode = ddlStatus.SelectedValue;
                ddlStatus.Visible = false;
                List<string> listFlow = new List<string>();
                foreach (var f in flowCode.Split('@'))
                {
                    if (!string.IsNullOrEmpty(f))
                    {
                        if (!(UserInfo.RoleId == "96" && f.StartsWith("1,")))
                        {
                            listFlow.Add(f);
                        }
                    }
                }
                return listFlow;
            }          
        }

        public override bool IsCheckPermission
        {
            get { return false; }
        }

        protected void RadToolBar1_Load(object sender, EventArgs e)
        {
            Telerik.Web.UI.RadToolBar toolbar = (Telerik.Web.UI.RadToolBar)sender;
            RadToolBarItem barItem = toolbar.FindItemByText("解锁退回");
            RadToolBarButton radButton = (RadToolBarButton)barItem;
            if (UserInfo.RoleId != "96")
            {
                radButton.Visible = false;
            }
        }
    }
}